<template>
  <a-space>
    <qc-save-button
      type="primary"
      :loading="btnLoading"
      :disabled="checkedKeys.length == 0"
      @click="saveRoleMenuCheckedKeyList"
    ></qc-save-button>
  </a-space>
  <div>
    <a-tree
      ref="menuTreeRef"
      checkable
      :tree-data="treeData"
      :replaceFields="replaceFields"
      v-model:checkedKeys="checkedKeys"
    >
    </a-tree>
  </div>
</template>
<script lang='ts'>
import { defineComponent, onMounted, reactive, ref, toRefs, watch } from 'vue'
import { getMenuTree } from '/@/kit/menu-kit'
import AsyncRoutes from '/@/router/routes/index'
import resourceAuthorityApi from '/@/api/org/resource-authority'
import { RESOURCE_TYPE, RESOURCE_CATEGORY } from './interface'
export default defineComponent({
  name: 'MenuPermission',
  props: {
    roleId: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const menuTreeRef = ref()
    const treeData = getMenuTree(AsyncRoutes)
    const checkedKeys = ref<string[]>([])
    const menuPermissionState = reactive({
      btnLoading: false,
      replaceFields: { children: 'children', title: 'title', key: 'menuId' },
      //查询选中的菜单keys
      getRoleCheckedKeyList: () => {
        resourceAuthorityApi.getRoleMenuResource(props.roleId).then((res) => {
          checkedKeys.value = res.data.data
        })
      },
      //保存角色菜单信息
      saveRoleMenuCheckedKeyList: () => {
        menuPermissionState.btnLoading = true
        const resourceAuthorityList = []

        checkedKeys.value.forEach((key) => {
          resourceAuthorityList.push({
            roleId: props.roleId,
            resourceId: key,
            resourceType: RESOURCE_TYPE.MENU,
            resourceCategory: RESOURCE_CATEGORY.USE,
          })
        })
        resourceAuthorityApi
          .addBatch(resourceAuthorityList, {
            roleId: props.roleId,
          })
          .finally(() => (menuPermissionState.btnLoading = false))
      },
    })

    onMounted(() => {
      menuPermissionState.getRoleCheckedKeyList()
    })

    return {
      menuTreeRef,
      treeData,
      checkedKeys,
      ...toRefs(menuPermissionState),
    }
  },
})
</script>
<style lang='less' scoped>
</style>